import { Component, ViewChild, ComponentFactoryResolver, Input, OnInit, ViewContainerRef, SimpleChanges } from '@angular/core';
import { EventService } from '../../../shared/service/event.service';
import { TabsService } from '../../../shared/service/tabs.service';
import { ComItem } from '../com-item';
import { AppGlobalService } from 'src/app/shared/service/app-global.service';
// tslint:disable-next-line:max-line-length
@Component({ selector: 'app-tab5Fixed-container', template: '<section>\n' + '<ng-template #tab5FixedContainer></ng-template>\n' + '</section>' })
export class Tab5FixedContainerComponent implements OnInit {
    @Input() subComs: ComItem[];
    @ViewChild('tab5FixedContainer', { read: ViewContainerRef }) myRef: ViewContainerRef;
    // tslint:disable-next-line:max-line-length
    constructor(private componentFactoryResolver: ComponentFactoryResolver, private eventService: EventService, public tabService: TabsService,
        public appGlobalService: AppGlobalService) { }
    ngOnInit() {
        if (this.eventService.eventEmit.listenerCount('refreshTab5FixedContainer') > 0) {
            this.eventService.eventEmit.removeListener('refreshTab5FixedContainer');
        }
        this.eventService.eventEmit.on('refreshTab5FixedContainer', () => {
            this.refreshComponent();
        });

        if (this.appGlobalService.eventService.eventEmit.listenerCount("updateTagsDataTb5" + localStorage.getItem('currentPath')) > 0) {
            this.appGlobalService.eventService.eventEmit.removeListener("updateTagsDataTb5" + localStorage.getItem('currentPath'));
        }
        this.appGlobalService.eventService.eventEmit.on("updateTagsDataTb5" + localStorage.getItem('currentPath'), res => {
            console.log("currentPath:" + localStorage.getItem('currentPath'))
            this.updateTagsData();
        });

    }
    updateTagsData() {

        let temArray: any = [];

        for (let i = 0; i < this.myRef.length; i++) {
            const tagInstance = this.myRef.get(i)["_view"].nodes[1].instance;
            if (tagInstance.tagData && tagInstance.tagData.shellDataId && tagInstance.tagData.shellDataId !== "0") {
                if (this.appGlobalService.getShellData(tagInstance.tagData.shellDataId)) {
                    // tagInstance.tagData = this.getDemoData();
                    if (this.appGlobalService.getShellData(tagInstance.tagData.shellDataId).remove === "true") {
                        temArray.push(this.myRef.get(i));
                    } else {
                        tagInstance.tagData = this.appGlobalService.getShellData(tagInstance.tagData.shellDataId);
                    }

                }
            }

        }
        if (temArray.length > 0) {
            temArray.forEach(element => {
                const index = this.myRef.indexOf(element)
                if (index >= 0) {
                    this.myRef.remove(index);
                    this.appGlobalService.deleteShellData(element["_view"].nodes[1].instance.tagData.shellDataId);
                    console.log("page appAnchor  remove tag:" + element["_view"].nodes[1].instance.tagData.shellDataId);
                }
            });
        }
    }
    changData(tagData, v) {
        if (tagData.shellDataId && tagData.shellDataId !== "0") {

            if (this.appGlobalService.getShellData(tagData.shellDataId)) {
                v.tagData = this.appGlobalService.getShellData(tagData.shellDataId);
                this.appGlobalService.deleteShellData(tagData.shellDataId);
                return v.tagData; // this.appGlobalService.getShellData(tagData.shellDataId);
            } else {
                return tagData;
            }

        } else {
            return tagData;
        }
    }
    // tslint:disable-next-line:use-life-cycle-interface
    ngOnChanges(changes: SimpleChanges): void { this.myRef.clear(); this.loadComponent(); }
    refreshComponent() {
        const that = this;
        if (localStorage.getItem("dataMapFixedTabContainer")) {
            const storeTagData = JSON.parse(localStorage.getItem("dataMapFixedTabContainer"));
            this.subComs = [];
            const cDataObj = storeTagData.currentData;
            const tags = cDataObj.tags;
            if (tags !== undefined && tags.length > 0) {
                const len = tags.length;
                for (let i = 0; i < len; i++) {
                    const tag = tags[i];
                    if (tag.linearLayout === 'body') {
                        this.tabService.getComsDataByStyle(tag.style, callData => {
                            if (callData) {
                                this.subComs.push(callData);
                                if (len - 1 === i) {
                                    if (!localStorage.getItem('refreshFooterComs')) {
                                        localStorage.setItem("refreshFooterComsTag", JSON.stringify({ clean: true }));
                                        // tslint:disable-next-line:max-line-length
                                        this.eventService.eventEmit.emit("testRefreshFooterComsContainer", "testRefreshFooterComsContainer");
                                    }
                                }
                            }
                        }, tag);
                    } else {
                        localStorage.setItem("refreshFooterComsTag", JSON.stringify(tag));
                        this.eventService.eventEmit.emit("testRefreshFooterComsContainer", "testRefreshFooterComsContainer");
                    }
                }
            }
            this.myRef.clear();
            localStorage.removeItem("dataMapFixedTabContainer");
            if (this.subComs !== undefined) {
                const l = this.subComs.length;
                for (let j = 0; j < l; j++) {
                    const v = this.subComs[j];
                    const factory = this.componentFactoryResolver.resolveComponentFactory(v.component);
                    const ref = this.myRef.createComponent(factory);
                    ref.instance.tagData = v.tagData;
                    ref.changeDetectorRef.detectChanges();
                }
            }
        }
    }
    loadComponent() {
        this.myRef.clear();
        const len = this.subComs.length;
        for (let i = 0; i < len; i++) {
            const v = this.subComs[i];
            const factory = this.componentFactoryResolver.resolveComponentFactory(v.component);
            const ref = this.myRef.createComponent(factory);
            ref.instance.tagData = this.changData(v.tagData, v);
        }
    }
}
